package org.jianfa.homework.user.controller;

import org.jianfa.homework.user.feign.CodeClient;
import org.jianfa.homework.user.model.HttpResponse;
import org.jianfa.homework.user.model.JianfaToken;
import org.jianfa.homework.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpCookie;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

@RestController
@CrossOrigin(origins = "*")
public class UserController {

    @Autowired
    private CodeClient codeClient;

    @Autowired
    private UserService userService;

    /**
     * 注册接口
     * true成功 0
     * false失败 1
     *
     * @param email
     * @param password
     * @param code
     * @return
     */
    @PostMapping("/user/register")
    public HttpResponse register(@RequestParam("email") String email,
                                 @RequestParam("password") String password,
                                 @RequestParam("code") String code,
                                 HttpServletResponse httpServletResponse) {
        //判断该用户是否已经注册过了
        boolean isRegistered = this.isRegistered(email);
        if (isRegistered) {
            HttpResponse httpResponse =
                    new HttpResponse.Builder().status(1).message("已经注册过了，请勿重复注册!").build();
            return httpResponse;
        }

        //校验验证码是否正确
        // 0正确 1错误 2超时
        Integer validate = codeClient.validate(email, code);
        if (validate.equals(1)) {
            HttpResponse httpResponse =
                    new HttpResponse.Builder().status(1).message("验证码错误，请重新输入验证码！").build();
            return httpResponse;
        }
        if (validate.equals(2)) {
            HttpResponse httpResponse =
                    new HttpResponse.Builder().status(1).message("验证码超时，请重新获取验证码！").build();
            return httpResponse;
        }

        //注册
        String token = UUID.randomUUID().toString();
        boolean register = userService.register(email, password, token);
        if (!register) {
            HttpResponse httpResponse =
                    new HttpResponse.Builder().status(1).message("注册失败！").build();
            return httpResponse;
        }
        Cookie cookie = new Cookie("Token", token);
        cookie.setPath("/");
        httpServletResponse.addCookie(cookie);

        HttpResponse httpResponse =
                new HttpResponse.Builder().status(0).message("").build();
        return httpResponse;
    }

    /**
     * 验证用户名密码合法性
     * 根据用户名和密码生成token, token存入数据库
     * token写入cookie
     * 登录成功返回邮箱地址，重定向到欢迎页
     *
     * @param email
     * @param password
     * @return
     */
    @PostMapping("/user/login")
    public HttpResponse login(@RequestParam("email") String email,
                              @RequestParam("password") String password,
                              HttpServletRequest httpServletRequest,
                              HttpServletResponse httpServletResponse) {

        //判断该用户是否已经注册过了
        boolean isRegistered = this.isRegistered(email);
        if (!isRegistered) {
            HttpResponse httpResponse =
                    new HttpResponse.Builder().status(1).message("还未注册，请先进行注册!").build();
            return httpResponse;
        }

        boolean authenticate = userService.authenticate(email, password);
        if (!authenticate) {
            HttpResponse httpResponse =
                    new HttpResponse.Builder().status(1).message("登陆失败，用户名或者密码错误!").build();
            return httpResponse;
        }

        Cookie[] cookies = httpServletRequest.getCookies();
        boolean hasToken = false;
        for (Cookie cookie : cookies) {
            String cookieName = cookie.getName();
            if ("Token".equals(cookieName)) {
                hasToken = true;
            }
        }

        if (!hasToken) {
            String token = UUID.randomUUID().toString();

            boolean update = userService.updateToken(email, token);
            if (!update) {
                HttpResponse httpResponse =
                        new HttpResponse.Builder().status(1).message("登陆失败，Token更新失败!").build();
                return httpResponse;
            }

            Cookie cookie = new Cookie("Token", token);
            cookie.setPath("/");
            httpServletResponse.addCookie(cookie);
        }

        HttpResponse httpResponse =
                new HttpResponse.Builder().status(0).message(email).build();
        return httpResponse;
    }

    /**
     * 登出
     *
     * @param email
     * @param httpServletResponse
     * @return
     */
    @PostMapping("/user/logout")
    public boolean logout(@RequestParam("email") String email,
                         HttpServletResponse httpServletResponse) {

        Cookie cookie = new Cookie("Token", null);
        cookie.setPath("/");
        cookie.setMaxAge(0);
        httpServletResponse.addCookie(cookie);
        return true;
    }


    /**
     * 是否已注册，根据邮箱判断
     * true代表已经注册过
     * false代表尚未注册
     *
     * @param email
     * @return
     */
    @GetMapping("/user/isRegistered")
    public boolean isRegistered(@RequestParam("email") String email) {
        boolean isRegistered = userService.isRegistered(email);
        return isRegistered;
    }

    /**
     * 根据token查询用户登录邮箱
     *
     * @return
     */
    @GetMapping("/user/info")
    public String info(HttpServletRequest httpServletRequest) {
        Cookie[] cookies = httpServletRequest.getCookies();
        String token = "";
        for (Cookie cookie : cookies) {
            String cookieName = cookie.getName();
            if ("Token".equals(cookieName)) {
                token = cookie.getValue();
            }
        }
        JianfaToken jianfaToken = userService.getJianfaToken(token);
        String email = jianfaToken.getEmail();
        return email;
    }

}
